package com.bank.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.bank.pojo.User;
import com.bank.utils.DbUtils;

/**
 * 登录用户，一个用户最多有四张银行卡
 * */
public class UserDAO {
	public static final Object[] columnNames = { "身份证", "姓名", "密码" };

	/**
	 * 根据用户名查询
	 */
	public static User getUser(String username) {
		String sql = "select id,real_name,password from bank_user where id=?";
		List param = new ArrayList<>();
		param.add(username);
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			connection = DbUtils.open();
			ps = DbUtils.preparedStatement(sql, param, connection);
			rs = ps.executeQuery();
			if (rs.next()) {
				User user = new User();
				user.setPassword(rs.getString("password"));
				user.setRealName(rs.getString("real_name"));
				user.setUsername(rs.getString("id"));
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			DbUtils.closeAll(connection, ps, null);
		}
		return null;
	}

	/**
	 * 修改密码
	 */
	public static void updatePassword(String username, String password) {
		String sql = "update bank_user set password=? where id=?";
		List param = new ArrayList<>();
		param.add(password);
		param.add(username);
		DbUtils.executeUpdate(sql, param);
	}

	/**
	 * 添加用户
	 */
	public static void add(String idNum, String name) {
		String sql = "insert into bank_user(id,real_name,password) values(?,?,?)";
		List param = new ArrayList<>();
		param.add(idNum);
		param.add(name);
		param.add("123456");
		DbUtils.executeUpdate(sql, param);
	}
}
